import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Table, Card, Badge, Radio, Input, DatePicker, Tooltip, Divider, Popconfirm, message, Form, Select, Modal,
  Button, Progress, Icon, Popover, Tag, Cascader
} from 'antd';
import querystring from 'querystring';
import moment from 'moment';
import { Link, routerRedux } from 'dva/router';
import TaskNameColumn from '../../components/TaskNameColumn';
import TrimSpan from '../../components/TrimSpan';
import MerchantTag from '../../components/MerchantTag';
import TaskStatusColumn from '../../components/TaskStatusColumn';
import TaskIdColumn from '../../components/TaskIdColumn';
import DateTimeColumn from '../../components/DateTimeColumn';
import PublisherChannelsPopover from '../../components/PublisherChannelsPopover';
import DockPanel from '../../components/DockPanel';
import Extension from '../../components/Extension';
import {TASK_TYPES, TASK_APPROVE_STATUS, SOURCE, RIGHT, CHANNELS, ACT_TYPE} from '../../constants';
import styles from './TableList.less';
import { queryTask, updateApproveTask } from '../../services/task';
import PublishModal from '../Approver/Modals/PublishModal';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;
const Search = Input.Search;

@connect(state => ({
  data: state.task.takerTask,
  loading: state.task.takerTaskLoading,
  currentUser: state.user.currentUser,
  suggestionUsers: state.team.suggestionUsers,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    nicaiCrx: null,
    version: '',
    modalVisible: false,
    transferModalVisible: false,
    transferSelectedKey: null,
    selectedRows: [],
    selectedRowKeys: [],
    modalLoading: false,
    extension: '',
    extensionVisible: false,
    channel_list: [],
    take_time_start: null,
    take_time_end: null,
    search: '',
    channel_name: undefined,
  }

  componentWillMount() {
    const { dispatch, currentUser, data: { pagination, approve_status } } = this.props;
    const query = querystring.parse(this.props.location.search.substr(1));
    if (currentUser._id) {
      dispatch({
        type: 'task/fetchTakerTasks',
        payload: {
          ...pagination,
          approve_status,
          user_id: currentUser._id,
        },
      });
    }
    const nicaiCrx = document.getElementById('nicaiCrx');
    nicaiCrx.addEventListener('setVersion', this.setVersion);
    nicaiCrx.addEventListener('setChannel', this.setChannel);
    if (!this.state.nicaiCrx) {
      this.setState({ nicaiCrx }, () => {
        setTimeout(() => {
          this.handleGetVersion();
        }, 1000);
      });
    }
  }
  
  componentWillUnmount() {
    const nicaiCrx = document.getElementById('nicaiCrx');
    nicaiCrx.removeEventListener('setChannel', this.setChannel);
    nicaiCrx.removeEventListener('setVersion', this.setVersion);
  }
  
  setVersion = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.version) {
      this.setState({
        version: data.version,
      })
    }
    if (data.error) {
      message.destroy();
      message.warn(data.msg, 60 * 60);
      this.setState({
        actsLoading: false,
      });
    } else {
      this.handleGetChannel();
    }
  }
  setChannel = (e) => {
    const data = JSON.parse(e.target.innerText);
    if (data.itemList) {
      this.setState({
        channel_list: data.itemList,
      });
    }
  }
  handleGetVersion = () => {
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('getVersion', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
  }
  handleGetChannel = () => {
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('getChannel', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
  }
  handleFetch = () => {
    const { dispatch, currentUser, data: { pagination, approve_status } } = this.props;
    const { search, channel_name, take_time_start, take_time_end } = this.state;
    dispatch({
      type: 'task/fetchTakerTasks',
      payload: { ...pagination, approve_status, user_id: currentUser._id, currentPage: 1, channel_name, take_time_start, take_time_end, search },
    });
  }
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, currentUser, data: { approve_status } } = this.props;
    const { search, channel_name, take_time_start, take_time_end } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      user_id: currentUser._id,
      approve_status,
      ...filters,
      search, channel_name, take_time_start, take_time_end,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'task/fetchTakerTasks',
      payload: params,
    });
    this.handleRowSelectChange([], []);
  }

  handlePublish = async (record) => {
    this.setState({
      selectedRowKeys: [record._id],
      selectedRows: [record],
    }, () => this.handlePublishAll());
  }
  handlePublishAll = async () => {
    const { selectedRows } = this.state;
    if (selectedRows.length > 10) {
      message.warn('最多一次发布10篇');
    } else {
      if (this.state.version) {
        this.props.dispatch({
          type: 'modal/showPublish',
          payload: {
            taskList: selectedRows,
            currentKey: 'writerList',
            version: this.state.version,
          }
        });
      } else {
        message.destroy();
        message.warn('请安装尼采创作平台插件！', 60 * 60);
      }
    }
  }
  handlePublishToTaobao = (task) => {
    const { currentUser } = this.props;
    this.state.nicaiCrx.innerText = JSON.stringify({ task: task, user: currentUser, channel_name: task.channel_name });
    const customEvent = document.createEvent('Event');
    customEvent.initEvent('publishToTaobao', true, true);
    this.state.nicaiCrx.dispatchEvent(customEvent);
  }
  handleSearch = (value, name) => {
    const { dispatch, data: { pagination, approve_status }, currentUser } = this.props;
    const { search, channel_name, take_time_start, take_time_end } = this.state;
    const values = {
      user_id: currentUser._id,
      approve_status,
      take_time_start,
      take_time_end,
      channel_name,
      search,
    };
    if (name === 'time') {
      values['take_time_start'] = value[0] ? value[0].format('YYYY-MM-DD 00:00:00') : '';
      values['take_time_end'] = value[1] ? value[1].format('YYYY-MM-DD 23:59:59') : '';
      if (value && value[0]) {
        this.setState({ take_time_start: value[0].format('YYYY-MM-DD 00:00:00'), take_time_end: value[1].format('YYYY-MM-DD 23:59:59') });
      } else {
        this.setState({ take_time_start: null, take_time_end: null });
      }
    } else {
      values[name] = value;
      this.setState({ [name]: value });
    }
    dispatch({
      type: 'task/fetchTakerTasks',
      payload: {
        currentPage: 1,
        pageSize: pagination.pageSize,
        ...values,
      }
    });
  }
  
  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  }
  
  changeApproveStatus = (e) => {
    const { dispatch, currentUser, data: { pagination } } = this.props;
    const { search, take_time_start, take_time_end, channel_name } = this.state;
    dispatch({
      type: 'task/fetchTakerTasks',
      payload: { ...pagination, channel_name, user_id: currentUser._id, approve_status: e.target.value, currentPage: 1, take_time_start, take_time_end, search }
    });
    this.handleRowSelectChange([], []);
  }

  handleShowPassModal = (record) => {
    this.setState({
      selectedRowKeys: [record._id],
      selectedRows: [record],
      modalVisible: true
    });
  }
  handlePassSearch = (value) => {
    if (value) {
      this.props.dispatch({
        type: 'team/searchUsers',
        payload: {
          nickname: value,
        }
      });
    }
  }
  handleSearchChange = (e) => {
    if (!e.target.value) {
      this.handleSearch(e.target.value, 'search')
    }
    this.setState({ search: e.target.value });
  }
  handlePass = () => {
    const { dispatch, currentUser, data: { pagination } } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          modalLoading: true,
        })
        dispatch({
          type: 'task/pass',
          payload: {
            target_user_id: values.target_user_id,
            user_id: currentUser._id,
            _id: this.state.selectedRowKeys[0],
          },
          callback: (result) => {
            if (result.error) {
              message.error(result.msg);
              this.setState({
                modalLoading: false,
              })
            } else {
              this.handleFetch();
              message.success(result.msg);
              this.handleRowSelectChange([], []);
              this.setState({
                modalVisible: false,
                modalLoading: false,
              })
            }
          }
        });
      }
    });
  }
  
  handleCopy = (record) => {
    // console.log(record)
    const {dispatch, currentUser, data: {pagination}} = this.props
    dispatch({
      type: 'task/pass',
      payload: {
        target_user_id: currentUser._id,
        user_id: currentUser._id,
        _id: record._id,
      },
      callback: (result) => {
        if (result.error) {
          message.error(result.msg)
        } else {
          this.handleFetch()
          message.success('复制成功')
        }
      }
    })
  }
  
  handleRemove = (record) => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'task/remove',
      payload: {
        _id: record._id,
        user_id: currentUser._id,
      },
      callback: (result) => {
        if (result.error) {
          message.error(result.msg);
        } else {
          message.success(result.msg);
          this.handleFetch();
        }
      },
    });
  }
  
  handleShowTransferModal = (record) => {
    // console.log('line 327', record._id)
    this.setState({
      transferSelectedKey: {_id: record._id},
      transferModalVisible: true,
    })
  }
  
  handleSetTransfer = (record, items) => {
    // console.log('line 325', record, items)
    let channelName = record[0]
    let _id = this.state.transferSelectedKey._id
    this.setState({
      transferSelectedKey: {
        _id: _id,
        formData: {
          activityId: items[2].activityId,
          template: items[2].value,
        },
        to_channel: channelName,
      }
    })
  }
  
  handleTransfer = () => {
    const {transferSelectedKey} = this.state
    // console.log('line 349', transferSelectedKey)
    if (transferSelectedKey) {
      this.props.dispatch({
          type: 'task/transfer',
          payload: {
            _id: transferSelectedKey._id,
            user_id: this.props.currentUser._id,
            formData: transferSelectedKey.formData,
            to_channel: transferSelectedKey.to_channel,
          },
          callback: (result) => {
            if (result.error) {
              message.error(result.msg);
              this.setState({
                modalLoading: false,
              })
            } else {
              // this.handleFetch();
              message.success(result.msg)
              this.setState({transferModalVisible: false, transferSelectedKey: null})
              this.setState({
                transferModalVisible: false,
                modalLoading: false,
              })
            }
          }
        },
      )
    }
  }
  
  transferSelect = () => {
    let options = []
    for (let i of CHANNELS) {
      let v1 = {
        value: i.name,
        label: i.name,
        children: [],
      }
      for (let j of i.activityList) {
        let v2 = {
          value: j.name,
          label: j.name,
          children: [],
        }
        if (j.templates != null) {
          for (let k of j.templates) {
            const taskType = TASK_TYPES.find(item => item.template === k)
            let v3 = {
              value: k,
              label: taskType ? taskType.text : '无',
              activityId: j.id,
            }
            v2.children.push(v3)
          }
        } else {
          v2.children = [{
            value: null,
            label: '无',
            activityId: j.id,
          }]
        }
        v1.children.push(v2)
      }
      options.push(v1)
    }
    return options
  }
  
  displayRender = (label) => {
    return label[label.length - 1]
  }
  
  handleShowDockPanel = (record, activeKey) => {
    this.props.dispatch({
      type: 'task/showDockPanel',
      payload: {
        _id: record._id,
        activeKey,
      },
    });
  }
  handleSearchChange = (e) => {
    if (!e.target.value) {
      this.handleSearch(e.target.value, 'search')
    }
    this.setState({ search: e.target.value });
  }
  handlePublishOk = () => {
    this.handleFetch();
    this.handleGetChannel();
    this.handleRowSelectChange([], []);
  }
  withdraw = async (record) => {
    const { currentUser } = this.props
    const result = await updateApproveTask({ status: 'ApproveWithdraw', task_id: record })
    if (!result.error) {
      message.success(result.msg)
    }
  }
  
  render() {
    const {data, loading, form: {getFieldDecorator}, suggestionUsers, currentUser} = this.props;
    const {modalVisible, transferModalVisible, selectedRowKeys, approveModalVisible, selectedRows, channel_list, take_time_start, take_time_end,} = this.state;
    const showPubish = currentUser.rights && currentUser.rights.indexOf(RIGHT.daren) >= 0;
    const columns = [
      {
        title: '标题',
        dataIndex: 'name',
        render: (val, record) => (
          <div>
            {/* <a target="_blank" href={record.taobao && record.taobao.url ? record.taobao.url : `/task/detail.html?_id=${record._id}`}> */}
            <a target="_blank" href={`/task/detail.html?_id=${record._id}`}>
              <TaskNameColumn text={val} length={19} />
            </a>
            <p>
              <MerchantTag text={record.merchant_tag} length={10} />
            </p>
          </div>
        ),
      },
      {
        title: '渠道',
        dataIndex: 'channel_name',
        render: (val, record) => {
          let title = val;
          let channel_name = val;
          if (record.formData && record.formData.activityName) {
            if (val) {
              title = `${title} / ${record.formData.activityName}`;
            } else {
              channel_name = record.formData.activityName;
              title = record.formData.activityName;
            }
          }
          title = `${ACT_TYPE[record.taobao.actType]}：${title}`;

          const distributionStatus = record.taobao.distributionStatus;
          let distribution = '';
          if (distributionStatus) {
            if (distributionStatus.status) distribution = distributionStatus.status;
            else if (distributionStatus.channels) {
              distribution = distributionStatus.channels.map((item, index) =>
                <Tag key={index} className={styles['ant-tag']}>{item}</Tag>);
            }
          }
          return (
            <div>
              <Tooltip placement="top" title={title}>
                {channel_name}
              </Tooltip>
              <div>{distribution}</div>
            </div>
          )
        },
      },
      {
        title: '状态',
        dataIndex: 'approve_status',
        render: (val, record) => {
          if (record.approve_status === TASK_APPROVE_STATUS.publishedToTaobao) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
                <DateTimeColumn value={record.publish_taobao_time} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.waitingForApprove) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
                <DateTimeColumn value={record.handin_time} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.taken) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
                <DateTimeColumn value={record.take_time} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.passed) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
                <DateTimeColumn value={record.approve_time} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.rejected) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
                <DateTimeColumn value={record.approve_time} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.taobaoRejected) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.taobaoAccepted) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
              </div>
            )
          } else if (record.approve_status === TASK_APPROVE_STATUS.waitingToTaobao) {
            return (
              <div>
                <TaskStatusColumn status={val} task={record} />
              </div>
            )
          }
        },
      },
      {
        title: '作者',
        dataIndex: 'taker_id',
        render: (val) => {
          if (val) {
            return val._id === currentUser._id ? '自己' : <TrimSpan text={val.nickname} length={4} />;
          }
          return '';
        },
      },
      {
        title: '阅读数',
        dataIndex: 'taobao',
        render: (val, record) => (
          record.taobao && record.taobao.summary ?
            record.taobao.summary.sumReadCnt.value
            :
            '暂无'
        ),
      },
      {
        title: <div>
          已修改次数
                <Tooltip placement="top" title="在阿里创作平台已修改次数">
            <Icon type="question-circle-o" style={{ marginLeft: 5 }} />
          </Tooltip>
        </div>,
        dataIndex: 'taobao.editStr',
      },
    ];
    const opera = {
      title: '操作',
      render: (record) => {
        if (record.approve_status === TASK_APPROVE_STATUS.taken) {
          return (
            <div>
              <Link to={`/writer/task/edit?_id=${record._id}`}>
                <span>编辑</span>
              </Link>
              {showPubish && <Divider type="vertical" />}
              {showPubish && <a onClick={() => this.handlePublish(record)}><PublisherChannelsPopover channel_list={channel_list} >发布</PublisherChannelsPopover></a>}
              {!record.project_id && <Divider type="vertical" />}
              {!record.project_id &&
                <Tooltip placement="top" title="将此稿复制一份发给他人或自己">
                  <a onClick={() => this.handleShowPassModal(record)}>转交</a>
                </Tooltip>
              }
              {(record.source === SOURCE.deliver || record.source === SOURCE.create || record.source === SOURCE.pass) && <Divider type="vertical" />}
              {(record.source === SOURCE.deliver || record.source === SOURCE.create || record.source === SOURCE.pass) &&
                <Popconfirm placement="left" title={`确认删除?`} onConfirm={() => this.handleRemove(record)} okText="确认" cancelText="取消">
                  <a>删除</a>
                </Popconfirm>
              }
              <Divider type="vertical" />
              <a onClick={() => this.handleShowDockPanel(record, 'OperationPane')}>
                动态
              </a>
              <Divider type="vertical"/>
              <Tooltip placement="top" title="将此稿转移到其它渠道，原渠道与目标渠道控件不同的内容会丢失，且此稿将被放入草稿箱">
                <a onClick={() => this.handleShowTransferModal(record)}>
                  转移
                </a>
              </Tooltip>
              <Divider type="vertical"/>
              <a onClick={() => this.handleCopy(record)}>
                复制
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.waitingForApprove) {
          return (
            <div>
              <Link to={`/writer/task/view?_id=${record._id}`}>
                查看
              </Link>
              <Divider type="vertical"/>
              <a onClick={() => this.handleShowDockPanel(record, 'OperationPane')}>
                动态
              </a>
              <Divider type="vertical" />
              <a onClick={() => this.withdraw(record)}>
                撤回
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.rejected) {
          return (
            <div>
              <Link to={`/writer/task/edit?_id=${record._id}`}>
                <span>编辑</span>
              </Link>
              {(record.source === SOURCE.deliver || record.source === SOURCE.create || record.source === SOURCE.pass) && <Divider type="vertical" />}
              {(record.source === SOURCE.deliver || record.source === SOURCE.create || record.source === SOURCE.pass) &&
                <Popconfirm placement="left" title={`确认删除?`} onConfirm={() => this.handleRemove(record)} okText="确认" cancelText="取消">
                  <a>删除</a>
                </Popconfirm>
              }
              <Divider type="vertical" />
              <a onClick={() => this.handleShowDockPanel(record, 'OperationPane')}>
                动态
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.passed) {
          return (
            <div>
              <Link to={`/writer/task/view?_id=${record._id}`}>
                查看
                </Link>
              <Divider type="vertical" />
              <a onClick={() => this.handleShowDockPanel(record, 'OperationPane')}>
                动态
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.waitingToTaobao) {
          return (
            <div>
              <a onClick={() => this.handleShowDockPanel(record, 'OperationPane')}>
                动态
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.publishedToTaobao) {
          return (
            <div>
              {record.taobao && record.taobao.url &&
                <a onClick={() => { this.setState({ extension: record.taobao.url, extensionVisible: true }) }}>
                  推广
                </a>
              }
              {record.taobao && record.taobao.url &&
                <Divider type="vertical" />
              }
              <a onClick={() => this.handleShowDockPanel(record, 'AnalyzePane')}>
                分析
              </a>
            </div>
          );
        } else if (record.approve_status === TASK_APPROVE_STATUS.taobaoRejected) {
          return (
            <div>
              {record.taobao && record.taobao.url &&
                <a onClick={() => { this.setState({ extension: record.taobao.url, extensionVisible: true }) }}>
                  推广
                </a>
              }
              {record.taobao && record.taobao.url && <Divider type="vertical" />}
              <a onClick={() => this.handleShowDockPanel(record, 'AnalyzePane')}>
                分析
              </a>
            </div>
          );
        } else {
          return (
            <div>
              <a onClick={() => { this.setState({ extension: record.taobao.url, extensionVisible: true }) }}>
                推广
              </a>
              <Divider type="vertical" />
              <a onClick={() => this.handleShowDockPanel(record, 'AnalyzePane')}>
                分析
              </a>
            </div>
          );
        }
      }
    };
    const rowSelection = (data.approve_status === 'taken' || data.approve_status === 'passed' || data.approve_status === 'waitingToTaobao') && showPubish ? {
      selectedRowKeys,
      hideDefaultSelections: true,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    } : null;
    columns.push(opera);

    const totals = data.totals;
    const radioButtons = [
      <Tooltip key="taken" placement="top" title="创作中">
        <RadioButton value="taken">草稿箱{totals.taken}</RadioButton>
      </Tooltip>,
      <Tooltip key="waitingForApprove" placement="top" title="等待审核">
        <RadioButton value="waitingForApprove">待审核 {totals.waitingForApprove}</RadioButton>
      </Tooltip>,
      <Tooltip key="rejected" placement="top" title="平台审核未通过">
        <RadioButton value="rejected">未通过 {totals.rejected}</RadioButton>
      </Tooltip>,
      <Tooltip key="passed" placement="top" title="平台审核已通过">
        <RadioButton value="passed">已通过 {totals.passed}</RadioButton>
      </Tooltip>,
    ];
    radioButtons.unshift(
      <Tooltip key="all" placement="top" title="全部状态">
        <RadioButton value="all">全部 {totals.all}</RadioButton>
      </Tooltip>);
    radioButtons.push(
      <Tooltip key="waitingToTaobao" placement="top" title="待发布到淘宝">
        <RadioButton value="waitingToTaobao">
          待发布 {totals.waitingToTaobao}
        </RadioButton>
      </Tooltip>,
      <Tooltip key="publishedToTaobao" placement="top" title="已发布到淘宝">
        <RadioButton value="publishedToTaobao">
          已发布 {totals.publishedToTaobao}
        </RadioButton>
      </Tooltip>,
    );

    radioButtons.push(
      <Tooltip key="taobaoRejected" placement="top" title="淘宝审核不通过">
        <RadioButton value="taobaoRejected">
          淘宝不通过 {totals.taobaoRejected}
        </RadioButton>
      </Tooltip>,
      <Tooltip key="taobaoAccepted" placement="top" title="淘宝审核已通过">
        <RadioButton value="taobaoAccepted">
          淘宝通过 {totals.taobaoAccepted}
        </RadioButton>
      </Tooltip>
    );
    return (
      <div>
        <div className={styles.searchBox}>
          <RadioGroup value={data.approve_status} onChange={this.changeApproveStatus}>
            {radioButtons}
          </RadioGroup>

        </div>
        <Card bordered={false} bodyStyle={{ padding: 14 }}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Search
                style={{ width: 260, float: 'right' }}
                placeholder="ID／名称／商家名称"
                onSearch={(value) => this.handleSearch(value, 'search')}
                onChange={this.handleSearchChange}
                value={this.state.search}
                enterButton
              />
              {!selectedRows.length > 0 && (
                <Select
                  allowClear
                  showSearch
                  style={{ width: 160, marginRight: 8 }}
                  placeholder="渠道"
                  onChange={(value) => this.handleSearch(value, 'channel_name')}
                  optionFilterProp="children"
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  value={this.state.channel_name}
                >
                  {CHANNELS.map(item => <Option key={item.id} value={item.name}>{item.name}</Option>)}
                </Select>
              )
              }
              {!selectedRows.length > 0 && (
                <RangePicker style={{ width: 240 }} onChange={(value) => this.handleSearch(value, 'time')}
                  value={take_time_start ? [moment(take_time_start), moment(take_time_end)] : []} />)
              }
              {!selectedRows.length > 0 && (
                <Tooltip placement="top" title="创建时间">
                  <Icon type="question-circle-o" />
                </Tooltip>)
              }
              {selectedRows.length > 0 && (data.approve_status === 'taken' || data.approve_status === 'passed' || data.approve_status === 'waitingToTaobao') && showPubish && (
                <span>
                  <Button icon="upload" type="default" onClick={this.handlePublishAll}>批量发布</Button>
                </span>)
              }
            </div>

            <Table
              loading={loading}
              dataSource={data.list}
              columns={columns}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                ...data.pagination,
              }}
              onChange={this.handleStandardTableChange}
              rowKey="_id"
              rowSelection={rowSelection}
            />
            <PublishModal k='writerList' onOk={this.handlePublishOk} />
            <DockPanel />
          </div>
        </Card>

        {modalVisible && <Modal
          title="选择转交对象"
          visible={modalVisible}
          onOk={this.handlePass}
          onCancel={() => { this.setState({ modalVisible: false }); this.handleRowSelectChange([], []); }}
          confirmLoading={this.state.modalLoading}
        >
          <FormItem
            label="用户"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            {getFieldDecorator('target_user_id', {
              initialValue: '',
              rules: [{ required: true, message: '请选择转交用户！' }],
            })(
              <Select
                style={{ width: '100%' }}
                mode="combobox"
                optionLabelProp="children"
                placeholder="搜索昵称指定转交用户"
                notFoundContent=""
                defaultActiveFirstOption={false}
                showArrow={false}
                filterOption={false}
                onSearch={this.handlePassSearch}
              >
                {suggestionUsers.map(item => <Option value={item._id} key={item._id}>{item.nickname}</Option>)}
              </Select>
            )}
          </FormItem>
        </Modal>}
        
        {transferModalVisible && <Modal
          title="选择转移对象"
          visible={transferModalVisible}
          onOk={this.handleTransfer}
          onCancel={() => {
            this.setState({transferModalVisible: false, transferSelectedKey: null})
          }}
          confirmLoading={this.state.modalLoading}
        >
          <FormItem
            label="频道"
            labelCol={{span: 4}}
            wrapperCol={{span: 20}}
          >
            {getFieldDecorator('target_user_id', {
              initialValue: '',
              rules: [{required: true, message: '请选择转移对象'}],
            })(
              <div>
                <Cascader
                  placeholder="请选择"
                  options={this.transferSelect()}
                  expandTrigger="hover"
                  displayRender={this.displayRender}
                  onChange={this.handleSetTransfer}
                />
              </div>
            )}
          </FormItem>
        </Modal>}
        <Extension visible={this.state.extensionVisible} url={this.state.extension}
                   onCancel={() => this.setState({extensionVisible: false})}/>
      </div>
    );
  }
}
